if(!cc.sys.isNative)
{
    window.io = require("SocketIO");
}

var Global = cc.Class({
    extends: cc.Component,
    statics: {
        ip:"",
        sio:null,
        isPinging:false,//是否开启心跳
        handlers:{},

        inter1:0,//定时器1
        inter2:0,//定时器2
        addHandler:function(event,fn){ //add服务器返回事件
            if(this.handlers[event]){
                return;
            }

            var handler = function(data){
			if(event != "disconnect" && typeof(data) == "string"){
                    //cc.log("chat "+data); 
                    try {
                        data = JSON.parse(data);
                    } catch (error) {
                        data = data;
                    }  
                }
                fn(data);
            };
            
            this.handlers[event] = handler; 
            if(this.sio){
                this.sio.on(event,handler);
            }
        },

        //连接服务器
        connect:function(fnConnect,fnError) {
            var self = this;
            this.serverTime = Date.now(); 
            var opts = {
                'reconnection':false,
                'force new connection': true,
                //'transports':['websocket', 'polling']
            }
        
            try{
                this.sio = window.io.connect(this.ip,opts);
            }catch(ex){
                // cc.log("socket connect erro:"+ex.message);
            }
            
            this.sio.on('connect',function(data){
                
                self.sio.connected = true;
                try {
                    self.isPinging = false;
                    fnConnect(data);
                } catch (error) {
                    // cc.log("connect error"+ error);
                    fnError();
                }
            });

            //发生错误时触发
            this.sio.on('error', function(error) {  
                self.close();
            });  
            
            //在断开连接时触发
            this.sio.on('disconnect',function(data){
                self.close();
            });

            //遇到连接错误
            this.sio.on('connect_error',function (){
                self.close();
            });

            //在连接超时后触发
            this.sio.on('connect_timeout',function (){
                self.close();
            });

            //试图重新连接时被解雇
            this.sio.on('reconnect_attempt',function (data){
                self.close();
            });

            //重新连接尝试错误时触发
            this.sio.on('reconnect_error',function (){
                self.close();
            });

            //无法重新连接时触发
            this.sio.on('reconnect_failed',function (){
                self.close();
            });
            
            for(var key in this.handlers){
                var value = this.handlers[key];
                if(typeof(value) == "function"){
                    this.sio.on(key,value);                          
                }
            } 
            this.startHearbeat();
        },
        
        //心跳包
        startHearbeat:function(){
            this.sio.on('rpongx',function(data){
                self.serverTime = data*1000;
                self.lastRecieveTime = Date.now(); 
            });
            this.lastRecieveTime = Date.now();
            var self = this;
            if(!self.isPinging){
                self.isPinging = true;
                cc.game.on(cc.game.EVENT_HIDE,function(){
                    self.ping();
                });
                this.inter1 = setInterval(function(){
                    if(self.sio){
                        self.ping();                
                    }
                }.bind(this),5000);
                this.inter2 = setInterval(function(){
                    if(self.sio){
                        if(Date.now() - self.lastRecieveTime > 10000){
                            cc.log("chat 未检测到心跳");
                            self.close();
                        }         
                    }
                }.bind(this),500);
            }   
        },

        //聊天室时间同步
        getServerTime:function(){
            return this.serverTime;
        },

        //心跳维持
        ping:function(){
           if(this.isConnect())
                this.send("pongx",Date.now());
        },

        //断连
        close:function(){
            clearInterval(this.inter1);
            clearInterval(this.inter2);
            if(this.sio && this.sio.connected){
                this.sio.connected = false;
                this.sio.disconnect();
            }
            this.sio = null;
        },

        //连接登录
        login:function(){
            var self = this;
            var sd = {
                token:User.getLoginToken(),
                userid:User.getUserCode(),
            };
            this.send("login",sd);
        },

        //发送房间聊天信息
        send_group_msg:function(msg){
            this.send("send_group_msg", msg);
        },

        //服务器是否连接
        isConnect:function(){
           return this.sio!=null?this.sio.connected:false;
        },

        //发送socket消息
        send:function(event,data){
            if(this.sio && this.sio.connected){
                if(data != null && (typeof(data) == "object")){
                    data = JSON.stringify(data);
                           
                }
                this.sio.emit(event,data);                
            }
        },

        //加入房间
        joinRoom:function(roomidStr,additionalStr,isrecont){
            var data ={
                roomid:roomidStr,
                additional:additionalStr,
                chatrecord:isrecont
            }
        
            this.send("join",data);
        },

        //离开房间
        leaveRoom:function(roomid){
            this.send("leave",roomid);
        }
    },
});